package cn.aishua.ui.main;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.aishua.MyApplication;
import cn.aishua.R;
import cn.aishua.R.drawable;
import cn.aishua.data.DataProvider;
import cn.aishua.data.FindDataParser;
import cn.aishua.data.FindDataParser.FindVendor;
import cn.aishua.data.PopupItem;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.main.PopupMaker.OnFinishListener;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.ui.vendor.VendorDetailActivity;
import cn.aishua.util.Constant;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.ImageLoader;
import cn.aishua.util.Rotate3dAnimation;
import cn.aishua.util.Utils;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;

public class VendorListActivity
    extends MapActivity
    implements LocationListener
{

    // ImageView imageNavHeader;
    //    ProgressBar progressBar1;
    FindDataParser mData;
    ListView listResult;
    ListResultAdapter mAdapter;

    final int MSG_FIND_DONE = 100;
    final int MSG_DOWNLOAD_IMAGE_DONE = 200;

    // ----------page -----------
    View viewLoadMore;
    TextView textLoadMore;
    int currPage = 1;

    //    ImageView vendor_list_header_btn1;
    //    ImageView vendor_list_header_btn2;

    TextView btn_filter_category;
    TextView btn_filter_canton;
    TextView btn_filter_sort;

    boolean init = false;

    boolean clickEnable = true;

    //    ArrayList<Object[]> trashBin = new ArrayList<Object[]>();

    LinearLayout linearPopupCanton;
    LinearLayout linearPopupCategory;

    // ----------------- criteria -----------------
    String strName;
    String strRate;
    int intPareCate;
    int intSubCate;
    int intCanton;
    int intBusiCirc;
    String strPrice;
    String SORT;

    //Whether the pop-up picker is shown in front.
    boolean popupShown = false;
    View whoPopped = null;

    // *******************used for map mode *************** 
    ViewFlipper viewFlipper;
    MapView mMapView;

    MKLocationManager mLocationManager;
    MapController mMapController;
    MyLocationOverlay myLocOverlay;

    Location location;

    boolean needToInitMap = true;

    Drawable icon1;
    Drawable icon2;
    Drawable icon3;
    Drawable icon4;
    Drawable icon5;

    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    MainActivityGroup parent;

    private View emptyView;

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_nav_header );
        ivLeftBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                navigationBar( v );
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "商户列表" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setImageResource( R.drawable.btn_map );
        ivRightBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                switchListView( v );
            }
        } );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.vendor_list );
        initPageHeader();

        initiateCretiria();

        init = true;
        init();
        init = false;
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if( isMapMode() )
        {
            ( (MyApplication) getApplication() ).getBMapMan().stop();
        }

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if( isMapMode() )
        {
            ( (MyApplication) getApplication() ).getBMapMan().start();
        }

    }

    private void initiateCretiria()
    {
        Intent intent = getIntent();
        strName = intent.getStringExtra( Constant.EXTRA_STR_CRITERIA_NAME );
        intPareCate = intent.getIntExtra( Constant.EXTRA_INT_CRITERIA_PARE_CATE, 0 );
        intSubCate = intent.getIntExtra( Constant.EXTRA_INT_CRITERIA_SUB_CATE, 0 );
        intCanton = intent.getIntExtra( Constant.EXTRA_INT_CRITERIA_CANTON, 0 );
        intBusiCirc = intent.getIntExtra( Constant.EXTRA_INT_CRITERIA_BUSI_CIRC, 0 );
        strRate = intent.getStringExtra( Constant.EXTRA_STR_CRITERIA_RATE );
        strPrice = intent.getStringExtra( Constant.EXTRA_STR_CRITERIA_AVER_PRICE );
    }

    /**
     * if this activity is from search (search input box or find vendor page) back button should
     * replace navigation button
     */
    private void fitInCase()
    {
        if( getIntent().getBooleanExtra( Constant.EXTRA_BOOL_IS_SEARCH, false ) )
        {
            ivLeftBtn.setImageResource( R.drawable.btn_left_arrow );
            ivLeftBtn.setOnClickListener( new OnClickListener()
            {
                public void onClick( View v )
                {
                    finish();
                }
            } );
        }

        final PopupMaker pMaker1 = new PopupMaker( this, intPareCate, intSubCate );
        pMaker1.make( linearPopupCategory, btn_filter_category, PopupMaker.TYPE_VENDOR_CATEGORY, new OnFinishListener()
        {
            public void finish()
            {
                intPareCate = pMaker1.pId;
                intSubCate = pMaker1.id;

                if( parent != null )
                {
                    parent.needsOwnBack = false;
                }

                switchViews( true );
                if( !init )
                    find(); // reset current page as 1
            }
        } );

        final PopupMaker pMaker2 = new PopupMaker( this, intCanton, intBusiCirc );
        pMaker2.make( linearPopupCanton, btn_filter_canton, PopupMaker.TYPE_CANTON, new OnFinishListener()
        {
            public void finish()
            {
                intCanton = pMaker2.pId;
                intBusiCirc = pMaker2.id;

                if( parent != null )
                {
                    parent.needsOwnBack = false;
                }
                switchViews( true );
                if( !init )
                    find(); // reset current page as 1
            }
        } );

        btn_filter_sort.setText( sortTypes[0] );
        SORT = "0";
    }

    public void switchListView( View view )
    {
        flipOver();

        if( isMapMode() ) // display vendor list of map mode
        {
            tvTitile.setText( "地图模式" );
            ivRightBtn.setImageResource( R.drawable.btn_list_view );
            ( (MyApplication) getApplication() ).getBMapMan().start();
            displayWidetsUsedInMap();

            if( needToInitMap )
            {
                initiateMap();
                needToInitMap = false;
                addMyLocationOverlay();
            }
            mLocationManager.requestLocationUpdates( this );
            addPinOverlay();
        }
        else
        {
            tvTitile.setText( "商户列表" );
            ivRightBtn.setImageResource( R.drawable.btn_map );
            ( (MyApplication) getApplication() ).getBMapMan().stop();
            displayWidetsUsedInList();
        }

        //        Intent intent = new Intent( this, MapModeActivity.class );
        //

        //        intent.putParcelableArrayListExtra( Constant.EXTRA_LIST_POPUP_ITEM, popupList );
        //
        //        intent.putExtra( Constant.EXTRA_INT_SELECTED_CATE, intPareCate );
        //        intent.putExtra( Constant.EXTRA_INT_SELECTED_SUB_CATE, intSubCate );
        //
        //        Log.d( "VendorList", "size of popupList: " + popupList.size() );
        //        Log.d( "VendorList", "size of mData: " + mData.count );
        //        startActivity( intent );
    }

    private ArrayList<PopupItem> generateListUsedInMap()
    {
        ArrayList<PopupItem> popupList = new ArrayList<PopupItem>();
        for( FindVendor data : mData.data )
        {
            String rate = (int) ( data.max_customer_rate * 100 ) + "%";
            String subCate = data.sub_category.size() > 0 ? data.sub_category.get( 0 ) : "";

            PopupItem popup = new PopupItem( data.id, data.name, data.pare_category, subCate, ""
                + (int) data.average_price, rate, FormatConverter.toDouble( data.lati ),
                FormatConverter.toDouble( data.longt ) );
            popupList.add( popup );
        }
        return popupList;
    }

    private void displayWidetsUsedInMap()
    {
        btn_filter_canton.setVisibility( View.GONE );
        btn_filter_sort.setVisibility( View.GONE );
        RelativeLayout rlLocate = (RelativeLayout) findViewById( R.id.vendor_list_btn_locate );
        rlLocate.setVisibility( View.VISIBLE );
    }

    private void displayWidetsUsedInList()
    {
        btn_filter_canton.setVisibility( View.VISIBLE );
        btn_filter_sort.setVisibility( View.VISIBLE );
        RelativeLayout rlLocate = (RelativeLayout) findViewById( R.id.vendor_list_btn_locate );
        rlLocate.setVisibility( View.GONE );
    }

    private void initiateMap()
    {
        initMapActivity( ( (MyApplication) getApplication() ).getBMapMan() );

        mMapView = (MapView) findViewById( R.id.vendor_list_map );
        mMapView.setBuiltInZoomControls( true );

        mMapController = mMapView.getController();
        mMapController.setZoom( 12 );

        icon1 = getResources().getDrawable( R.drawable.icon_pin_1 );
        icon2 = getResources().getDrawable( R.drawable.icon_pin_2 );
        icon3 = getResources().getDrawable( R.drawable.icon_pin_3 );
        icon4 = getResources().getDrawable( R.drawable.icon_pin_4 );
        icon5 = getResources().getDrawable( R.drawable.icon_pin_5 );
    }

    private void init()
    {
        //        // clean memory
        //        for( int i = 0; i < trashBin.size(); i++ )
        //        {
        //            Object[] objs = trashBin.get( i );
        //            ( (ImageView) objs[0] ).setImageResource( R.drawable.member_pic );
        //            ( (Bitmap) objs[1] ).recycle();
        //        }
        //        trashBin.clear();
        parent = (MainActivityGroup) getParent();
        emptyView = findViewById( R.id.vendor_list_listEmpty );

        btn_filter_category = (TextView) findViewById( R.id.btn_filter_category );
        btn_filter_canton = (TextView) findViewById( R.id.btn_filter_canton );
        btn_filter_sort = (TextView) findViewById( R.id.btn_filter_sort );

        viewFlipper = (ViewFlipper) findViewById( R.id.vendor_list_vf );

        //        progressBar1 = (ProgressBar) findViewById( R.id.vendor_list_progressBar1 );
        //        progressBar1.setVisibility( View.GONE );

        listResult = (ListView) findViewById( R.id.vendor_list_listResult );
        listResult.setEmptyView( emptyView );
        emptyView.setVisibility( View.INVISIBLE );

        viewLoadMore = getLayoutInflater().inflate( R.layout.footer_btn, null );
        textLoadMore = (TextView) viewLoadMore.findViewById( R.id.textLoadMore );
        viewLoadMore.setOnClickListener( textLoadMoreClickListener );
        //        listResult.addFooterView( viewLoadMore );
        listResult.setFooterDividersEnabled( false );

        linearPopupCanton = (LinearLayout) findViewById( R.id.linearPopupCanton );
        linearPopupCanton.setVisibility( View.GONE );

        linearPopupCategory = (LinearLayout) findViewById( R.id.linearPopupCategory );
        linearPopupCategory.setVisibility( View.GONE );

        btn_filter_category.setOnClickListener( new OnClickListener()
        {
            public void onClick( View v )
            {
                switchViews( false );
                linearPopupCategory.setVisibility( View.VISIBLE );
                if( parent != null )
                {
                    parent.needsOwnBack = true;
                }
            }
        } );

        btn_filter_canton.setOnClickListener( new OnClickListener()
        {
            public void onClick( View v )
            {
                switchViews( false );
                linearPopupCanton.setVisibility( View.VISIBLE );
                if( parent != null )
                {
                    parent.needsOwnBack = true;
                }
            }
        } );

        btn_filter_sort.setOnClickListener( btnFilterSortClickListener );

        fitInCase();

        find();
    }

    String[] sortTypes = new String[] { "默认排序", "人均降序", "人均升序", "返利降序", "返利升序" };

    OnClickListener btnFilterSortClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            new AlertDialog.Builder( VendorListActivity.this ).setItems( sortTypes,
                new DialogInterface.OnClickListener()
                {
                    public void onClick( DialogInterface dialog, int which )
                    {
                        btn_filter_sort.setText( sortTypes[which] );
                        SORT = String.valueOf( which );

                        find();
                        dialog.dismiss();
                    }
                } ).show();

        }
    };

    Handler mHandler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {
            switch( msg.what )
            {
                case MSG_FIND_DONE:
                    //                    progressBar1.setVisibility( View.GONE );
                    emptyView.setVisibility( View.VISIBLE );

                    if( isMapMode() )
                    {
                        addPinOverlay();
                    }

                    //                    else
                    //                    {

                    Log.d( "VendorList", "footerView count: " + listResult.getFooterViewsCount() );
                    if( msg.arg1 == 0 ) // 0 means no more items
                    {
                        //                            viewLoadMore.setVisibility( View.GONE );

                        if( listResult.getFooterViewsCount() > 0 )
                        {
                            Log.d( "VendorList", "remove footer view" );
                            listResult.removeFooterView( viewLoadMore );
                        }
                    }
                    else
                    {
                        //                        listResult.addFooterView( viewLoadMore );
                        //                            viewLoadMore.setVisibility( View.VISIBLE );
                        if( listResult.getFooterViewsCount() == 0 )
                        {
                            Log.d( "VendorList", "remove footer view" );
                            listResult.addFooterView( viewLoadMore );
                        }
                    }

                    Log.d( "VendorListActivity", "MSG_FIND_DONE" );
                    Log.d( "VendorListActivity", "msg.arg1: " + msg.arg1 );
                    Log.d( "VendorListActivity", "currPage" + currPage );
                    if( currPage == 1 ) // first page needs to initiate adapter
                    {
                        listResult.setVisibility( View.VISIBLE );
                        mAdapter = new ListResultAdapter( VendorListActivity.this );
                        listResult.setAdapter( mAdapter );
                    }
                    else
                    // page after first only needs to notify data change
                    {
                        mAdapter.notifyDataSetChanged();
                        textLoadMore.setText( "加载更多" );
                        textLoadMore.setEnabled( true );
                    }
                    currPage++;

                    //                    }

                    break;
                case MSG_DOWNLOAD_IMAGE_DONE:
                    Object[] objs = (Object[]) msg.obj;

                    WeakReference<Bitmap> wfBitmap = new WeakReference<Bitmap>( (Bitmap) objs[1] );

                    ( (ImageView) objs[0] ).setImageBitmap( wfBitmap.get() );
                    //                    trashBin.add( new Object[] { (ImageView) objs[0], (Bitmap) objs[1] } );
                    break;
            }
        }
    };

    private void find()
    {
        Log.d( "VendorList", "find()" );
        //        progressBar1.setVisibility( View.VISIBLE );
        listResult.setVisibility( View.GONE );

        new DataExchangeAsyncTask( this, "查找商户" )
        {

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().findVendors( params );

            }

            @Override
            protected void handleSuccResponse( String strJson ) throws Exception
            {
                // FIXME
                mData = new FindDataParser();
                currPage = 1;
                // TODO
                //                handleListFooter( mData.refresh( MyKakaTestJsonData.FIND_VENDORS ) );
                int need = mData.refresh( strJson );
                //                handleListFooter( mData.refresh( strJson ) );
                mHandler.obtainMessage( MSG_FIND_DONE, need, 0 ).sendToTarget();

            }
        }.execute( strName, "" + intPareCate, "" + intSubCate, "" + intCanton, "" + intBusiCirc, strPrice, strRate,
            "1", SORT );// reset current page as 1

    }

    class ViewHolder
    {
        public int id;
        public TextView textRate;
        public TextView textName;
        public ImageView imagePic;
        public TextView textAvgPrice;
        public TextView textDistance;
        public TextView textTag;
        public TextView textSubCat;
        public TextView textBusinessCir;

    }

    class ListResultAdapter
        extends BaseAdapter
    {

        Context mContext;

        public ListResultAdapter(Context context)
        {
            mContext = context;
        }

        public int getCount()
        {
            return mData.count;
        }

        public Object getItem( int position )
        {
            return position;
        }

        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            l( "position " + position + ", convertView " + convertView );
            ViewHolder holder = null;
            if( convertView == null )
            {
                holder = new ViewHolder();
                convertView = LayoutInflater.from( mContext ).inflate( R.layout.vendor_item, null );

                holder.textRate = (TextView) convertView.findViewById( R.id.vendor_item_tv_rebate );
                holder.textName = (TextView) convertView.findViewById( R.id.vendor_item_tv_vendor_name );
                holder.imagePic = (ImageView) convertView.findViewById( R.id.vendor_item_iv_pic );
                holder.textAvgPrice = (TextView) convertView.findViewById( R.id.vendor_item_tv_average_price );
                holder.textDistance = (TextView) convertView.findViewById( R.id.vendor_item_tv_distance );
                holder.textTag = (TextView) convertView.findViewById( R.id.vendor_item_tv_tags );
                //                holder.textSubCat = (TextView) convertView.findViewById( R.id.textSubCat );
                //                holder.textBusinessCir = (TextView) convertView.findViewById( R.id.textBusinessCir );

                convertView.setTag( holder );
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            final FindVendor d = mData.data.get( position );
            //            holder.imagePic.setImageResource( R.drawable.default_vendor_pic );

            String rate = (int) ( d.max_customer_rate * 100 ) + "";

            holder.textRate.setText( rate );
            holder.textName.setText( d.name );
            holder.textAvgPrice.setText( "" + (int) d.average_price );
            holder.textDistance.setText( Utils.doDistance( d.distance ) );

            generateTags( d.merchant_tags, holder.textTag );
            //            holder.textTag.setText( d.merchant_tags.size() > 0 ? d.merchant_tags.get( 0 ) : "" );
            //            holder.textSubCat.setText( subCate );
            //            holder.textBusinessCir.setText( d.business_circle );
            holder.id = d.id;

            //            boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
            //                SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
            //
            //            if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
            //            {
            //                new DownloadPicTask( VendorListActivity.this, holder.imagePic ).execute( d.file_url );
            //            }
            ImageLoader.getInstance( VendorListActivity.this ).loadImage( d.file_url, holder.imagePic );

            //            byte[] temp = null;
            //            if( ( temp = DataProvider.getInstance( VendorListActivity.this ).tryGetTempPic( holder.id ) ) != null )
            //            {
            //                // reuse pic from database
            //
            //                try
            //                {
            //                    Bitmap tempBitmap = BitmapFactory.decodeByteArray( temp, 0, temp.length );
            //                    WeakReference<Bitmap> wrBitmap = new WeakReference<Bitmap>( tempBitmap );
            //                    holder.imagePic.setImageBitmap( wrBitmap.get() );
            //                    tempBitmap = null;
            //                }
            //                catch( OutOfMemoryError e )
            //                {
            //                    Log.e( "VendorListActivity", e.getMessage() );
            //                }
            //
            //            }
            //            else
            //            {
            //                boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
            //                    SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
            //
            //                if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
            //                {
            //                    downloadImage( holder.imagePic, d.file_url, holder.id );
            //                }
            //            }

            // set background
            if( position % 2 == 1 )
            {
                convertView.setBackgroundResource( drawable.list_item_bg_color_2 );
            }
            else
            {
                convertView.setBackgroundResource( drawable.list_item_bg_color_1 );
            }

            convertView.setOnClickListener( new OnClickListener()
            {
                public void onClick( View v )
                {
                    if( !clickEnable )
                        return;
                    l( "item clicked with id " + d.id );
                    // TODO
                    toVendorDetail( d.id );
                }
            } );

            return convertView;
        }

        private void generateTags( ArrayList<String> merchant_tags, TextView textTag )
        {
            StringBuffer sbStrTags = new StringBuffer();
            if( merchant_tags != null )
            {
                int size = merchant_tags.size();
                for( int i = 0; i < size; i++ )
                {
                    String tag = merchant_tags.get( i );
                    if( i > 0 )
                    {
                        sbStrTags.append( "  " );
                    }
                    sbStrTags.append( tag );
                }
            }

            textTag.setText( sbStrTags.toString().trim() );
        }

        private void downloadImage( final ImageView v, final String urlString, final int id )
        {
            new Thread()
            {
                public void run()
                {
                    l( "download go! for id :" + id );
                    try
                    {
                        URL url = new URL( urlString );
                        l( urlString );
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput( true );
                        conn.connect();
                        InputStream in = conn.getInputStream();

                        Bitmap tempBitmap = BitmapFactory.decodeStream( in );

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        tempBitmap.compress( CompressFormat.JPEG, 30, out );

                        tempBitmap.recycle();
                        tempBitmap = null;

                        // Save the bitmap
                        DataProvider.getInstance( VendorListActivity.this ).insertTempPic( id, out.toByteArray() );

                        l( "saved for " + id );
                        Bitmap newBitmap = BitmapFactory.decodeByteArray( out.toByteArray(), 0,
                            out.toByteArray().length );
                        out.close();
                        Object[] objs = { v, newBitmap };
                        mHandler.obtainMessage( MSG_DOWNLOAD_IMAGE_DONE, objs ).sendToTarget();
                        newBitmap = null;
                        in.close();
                        in = null;
                        System.gc();
                    }
                    catch( Exception e )
                    {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }

    OnClickListener textLoadMoreClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            textLoadMore.setText( "正在加载中..." );
            textLoadMore.setEnabled( false );

            new DataExchangeAsyncTask( VendorListActivity.this, null )
            {

                @Override
                protected HttpResponse sendRequest( String... params )
                {
                    return HttpRequestUtil.getInstance().findVendors( params );
                }

                @Override
                protected void handleSuccResponse( String strJson ) throws Exception
                {
                    int need = mData.refresh( strJson );

                    mHandler.obtainMessage( MSG_FIND_DONE, need, 0 ).sendToTarget();

                }
            }.execute( strName, "" + intPareCate, "" + intSubCate, "" + intCanton, "" + intBusiCirc, strPrice, strRate,
                "" + currPage, SORT ); // every time pressed, current page will plus 1
        }
    };

    private void switchViews( boolean enabled )
    {
        ivLeftBtn.setEnabled( enabled );
        ivRightBtn.setEnabled( enabled );

        btn_filter_category.setEnabled( enabled );
        btn_filter_canton.setEnabled( enabled );
        btn_filter_sort.setEnabled( enabled );

        listResult.setEnabled( enabled );

        clickEnable = enabled;
    }

    private void l( String s )
    {
        android.util.Log.d( "test", s );
    }

    public void navigationBar( View view )
    {
        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.handleNaviBar();
    }

    public void toVendorDetail( View view )
    {
        Intent intent = new Intent( this, VendorDetailActivity.class );
        ViewHolder holder = (ViewHolder) view.getTag();
        intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, holder.id );
        startActivity( intent );
    }

    public void toVendorDetail( int vendorID )
    {
        Intent intent = new Intent( this, VendorDetailActivity.class );
        intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, vendorID );
        startActivity( intent );
    }

    /*
     * map mode --------------------------- start
     */

    private void flipOver()
    {
        float halfWidth = viewFlipper.getWidth() / 2.0f;
        float halfHeight = viewFlipper.getHeight() / 2.0f;
        int duration = 500;
        int depthz = 0;

        Rotate3dAnimation in = new Rotate3dAnimation( -90, 0, halfWidth, halfHeight, depthz, false );
        in.setDuration( duration );
        in.setStartOffset( duration );
        viewFlipper.setInAnimation( in );
        Rotate3dAnimation out = new Rotate3dAnimation( 0, 90, halfWidth, halfHeight, depthz, false );
        out.setDuration( duration );
        viewFlipper.setOutAnimation( out );
        viewFlipper.showNext();
    }

    /**
     * check whether the page is displaying map mode
     * 
     * @return
     */
    private boolean isMapMode()
    {
        return viewFlipper.getCurrentView().getId() == R.id.vendor_list_map;
    }

    private void addPinOverlay()
    {
        ArrayList<PopupItem> popupList = generateListUsedInMap();

        List<Overlay> overlays = mMapView.getOverlays();

        PinsOverlay pinsOverlay = null;

        if( overlays.get( overlays.size() - 1 ) instanceof PinsOverlay )
        {
            pinsOverlay = (PinsOverlay) overlays.get( overlays.size() - 1 );
            //            overlays.add
        }
        else
        {
            pinsOverlay = new PinsOverlay( icon1 );
            overlays.add( pinsOverlay );
        }

        pinsOverlay.clear();

        boolean hasSetCenter = false;
        // filter the marker based on user's selection
        if( popupList != null && popupList.size() > 0 )
        {
            Log.d( "MapModeActivity", "size of popupList: " + popupList.size() );
            /*
             * divide the list into 5 categories {"id":1,"name":"餐饮美食"} {"id":2,"name":"休闲娱乐"}
             * {"id":3,"name":"商场超市"} {"id":4,"name":"生活服务"} {"id":5,"name":"酒店旅游"}
             */
            //            List<PopupItem> finalList = new ArrayList<PopupItem>();

            for( PopupItem popupItem : popupList )
            {
                Log.d( "MapModeActivity", "vendor name:" + popupItem.getVendorName() );

                String cate = popupItem.getCategory();
                Log.d( "MapModeActivity", "cate: " + cate );

                GeoPoint p = new GeoPoint( (int) ( popupItem.getX() * 1e6 ), (int) ( popupItem.getY() * 1e6 ) );
                // set the initial place
                if( !hasSetCenter )
                {
                    mMapController.setCenter( p );
                    hasSetCenter = true;
                }

                popupItem.setMarker( makeDrawable( cate ) );
                pinsOverlay.addItem( popupItem );
            }

        }

        if( !hasSetCenter )
        {
            mMapController.setCenter( new GeoPoint( (int) ( 30.653245 * 1e6 ), (int) ( 104.0753 * 1e6 ) ) );
        }

        mMapView.invalidate();

    }

    public class PinsOverlay
        extends ItemizedOverlay<OverlayItem>
    {
        //        private List<PopupItem> popupList;
        private List<OverlayItem> itemList = new ArrayList<OverlayItem>();

        public PinsOverlay(Drawable defaultMarker)
        {
            super( boundCenterBottom( defaultMarker ) );
            populate();
        }

        public void addItem( OverlayItem item )
        {
            itemList.add( item );
            populate();
        }

        public void clear()
        {
            itemList.clear();
            populate();
        }

        @Override
        protected OverlayItem createItem( int i )
        {
            OverlayItem item = itemList.get( i );
            item.setMarker( boundCenterBottom( item.getMarker( i ) ) );
            return itemList.get( i );
        }

        @Override
        public int size()
        {
            Log.d( "MapModeActivity", "size of itemList" + itemList.size() );
            return itemList.size();
        }

        @Override
        protected boolean onTap( int i )
        {
            popupWin( i ); // animate to some place which is better to show the popup window
            return true;
        }

        private void popupWin( int i )
        {

            GeoPoint geoPoint = itemList.get( i ).getPoint();

            Projection p = mMapView.getProjection();
            Point point = p.toPixels( geoPoint, null );
            GeoPoint newGeoPoint = p.fromPixels( point.x + 138, point.y - 12 );

            mMapController.animateTo( newGeoPoint );

            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate( R.layout.pop_view, null );

            // initiate text views
            TextView tvName = (TextView) view.findViewById( R.id.pop_view_name );
            TextView tvPrice = (TextView) view.findViewById( R.id.pop_view_price );
            TextView tvRate = (TextView) view.findViewById( R.id.pop_view_rate );

            PopupItem popup = (PopupItem) itemList.get( i );
            tvName.setText( popup.getVendorName() );
            tvPrice.setText( popup.getAveragePrice() );
            tvRate.setText( popup.getRate() );

            view.setOnClickListener( new TapListener( popup.getVendorId() ) );

            PopupWindow popupWin = new PopupWindow( view, 415, 111 );

            popupWin.setFocusable( true );
            popupWin.setOutsideTouchable( true );
            popupWin.update();
            popupWin.setBackgroundDrawable( new BitmapDrawable() );
            popupWin.showAtLocation( mMapView, Gravity.CENTER, 0, 0 );

        }

        class TapListener
            implements OnClickListener
        {
            private int id;

            public TapListener(int id)
            {
                this.id = id;
            }

            public void onClick( View v )
            {
                Log.d( "VendorListActivity", "popup view - onClick()" );
                Intent intent = new Intent( getApplicationContext(), VendorDetailActivity.class );
                intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, id );
                startActivity( intent );
            }

        }

    }

    private Drawable makeDrawable( String category )
    {
        Drawable marker = null;

        //        divide the list into 5 categories {"id":1,"name":"餐饮美食"} {"id":2,"name":"休闲娱乐"}
        //        * {"id":3,"name":"商场超市"} {"id":4,"name":"生活服务"} {"id":5,"name":"酒店旅游"}
        if( "餐饮美食".equals( category ) )
        {
            marker = icon1;
        }
        else if( "休闲娱乐".equals( category ) )
        {
            marker = icon2;
        }
        else if( "商场超市".equals( category ) )
        {
            marker = icon3;
        }
        else if( "生活服务".equals( category ) )
        {
            marker = icon4;
        }
        else if( "酒店旅游".equals( category ) )
        {
            marker = icon5;
        }
        else
        {
            marker = icon1;
        }

        //        int width = marker.getIntrinsicWidth();
        //        int height = marker.getIntrinsicHeight();
        //
        //        Log.d( "VendorList", "marker.getIntrinsicWidth(): " + width );
        //        Log.d( "VendorList", "getIntrinsicHeight(): " + height );
        //
        //        Rect rect = marker.getBounds();
        //        rect.offset( -24, -72 );
        //        marker.setBounds( rect );

        return marker;
    }

    private void addMyLocationOverlay()
    {
        mLocationManager = ( (MyApplication) getApplication() ).getBMapMan().getLocationManager();
        mLocationManager.enableProvider( (int) MKLocationManager.MK_GPS_PROVIDER );

        myLocOverlay = new MyLocationOverlay( this, mMapView );
        myLocOverlay.enableMyLocation();
        myLocOverlay.disableCompass();
        //        LocationData locData = new LocationData();
        mMapView.getOverlays().add( myLocOverlay );
    }

    @Override
    public void onLocationChanged( Location location )
    {
        this.location = location;
    }

    @Override
    public void onBackPressed()
    {
        View whoPopped = null;
        if( linearPopupCanton.getVisibility() == View.VISIBLE )
        {
            whoPopped = linearPopupCanton;
        }

        if( linearPopupCategory.getVisibility() == View.VISIBLE )
        {
            whoPopped = linearPopupCategory;
        }

        if( whoPopped != null )
        {
            whoPopped.setVisibility( View.GONE );
            switchViews( true );
            if( parent != null )
            {
                parent.needsOwnBack = false;
            }
        }
        else
        {
            finish();
        }
    }

    public void locate( View view )
    {
        if( location != null )
        {
            final GeoPoint pt = new GeoPoint( (int) ( location.getLatitude() * 1000000 ),
                (int) ( location.getLongitude() * 1000000 ) );
            // 将当前位置设置为地图的中心  
            mMapController.setCenter( pt );
            mMapView.invalidate();
        }
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }
}
